<template>
  <div class="submit-container">
    <div class="submit-content">
      <el-form
        ref="formRef"
        :model="registerStore.userInfo"
        :rules="rules"
        label-width="100px"
        :loading="loading"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="账号:" prop="userAccount">
              {{ registerStore.userInfo.userAccount }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="昵称:" prop="nickname">
              {{ registerStore.userInfo.nickname }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="性别" prop="gender">
              <DictLabel v-model="registerStore.userInfo.gender" code="GENDER" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="出生日期" prop="birthDate">
              {{ dayjs(registerStore.userInfo.birthDate).format("YYYY-MM-DD") }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
            <div class="mail-container">
              <el-form-item label="邮箱:" prop="email">
                <div style="display: flex">
                  <el-input
                    v-model="registerStore.userInfo.email"
                    :disabled="countdown > 0"
                    placeholder="请输入邮箱"
                  />
                  <el-icon v-if="checked && !mailLoading" style="margin: 10px; color: green">
                    <CircleCheck />
                  </el-icon>
                  <el-icon v-if="mailLoading" style="margin: 10px; color: green">
                    <Loading />
                  </el-icon>
                </div>
              </el-form-item>
              <el-button v-if="countdown <= 0" type="success" @click="handlerCaptcha">
                {{ buttonText }}
              </el-button>
              <el-button v-else type="info">
                {{ buttonText }}
              </el-button>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item v-if="send" label="验证码:" prop="captcha">
              <el-input v-model="captcha" placeholder="请输入验证码" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="submit-footer">
      <el-button type="primary" @click="handlerPrevStep">上一步</el-button>
      <el-button type="primary" @click="handlerRegister">注册</el-button>
    </div>
  </div>
</template>
<script lang="ts" setup>
import dayjs from "dayjs";
import FingerprintJS from "@fingerprintjs/fingerprintjs";
import DictLabel from "@/components/Dict/DictLabel.vue";
import { useAppStore } from "@/store";
import { useRegisterStore } from "@/store/modules/register.store";
import { useUserStore } from "@/store";
import { LocationQuery, useRoute } from "vue-router";
const route = useRoute();
const userStore = useUserStore();
const appStore = useAppStore();

import UserAPI from "@/api/system/user.api";
import EmailApi from "@/api/system/email.api";
const emit = defineEmits(["complete", "prev"]);
const formRef = ref();
const captcha = ref();
const send = ref(false);
const loading = ref(false);
const checked = ref(false);
const mailLoading = ref(false);

// 倒计时秒数
const countdown = ref(0);

// 定时器引用
const timer = ref();
// 是否正在倒计时
const isCounting = ref(false);

// 计算按钮显示的文本
const buttonText = computed(() => {
  return isCounting.value ? `${countdown.value}秒后重新发送` : "获取验证码";
});

// 邮箱格式验证规则
const validateEmailFormat = (rule: any, value: any, callback: any) => {
  checked.value = false;
  // 简单的邮箱格式正则
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

  if (!value) {
    callback(new Error("请输入邮箱地址"));
  } else if (!emailRegex.test(value)) {
    callback(new Error("邮箱格式不正确"));
  } else {
    checked.value = true;
    callback();
  }
}; // 验证码校验
const validateCaptcha = (rule: any, value: any, callback: any) => {
  if (send.value && !captcha.value) {
    callback(new Error("请输入验证码"));
  } else {
    callback();
  }
};

// 邮箱唯一性验证规则
const validateEmailUnique = (rule: any, value: any, callback: any) => {
  mailLoading.value = true;
  UserAPI.checkEmail(value)
    .then((isAvailable) => {
      checked.value = isAvailable;
      if (isAvailable) {
        callback();
      } else {
        callback(new Error("该邮箱已被注册"));
      }
    })
    .catch(() => {
      callback(new Error("验证失败，请稍后重试"));
    })
    .finally(() => {
      mailLoading.value = false;
    });
};

// 开始倒计时
const startCountdown = (time: number) => {
  isCounting.value = true;
  countdown.value = time;

  timer.value = setInterval(() => {
    countdown.value--;

    if (countdown.value <= 0) {
      clearInterval(timer.value);
      isCounting.value = false;
    }
  }, 1000);
};
// 组件卸载前清除定时器
onBeforeUnmount(() => {
  if (timer.value) {
    clearInterval(timer.value);
  }
});
const rules = reactive({
  email: [
    { required: true, message: "请输入邮箱地址", trigger: "blur" },
    { validator: validateEmailFormat, trigger: "blur" },
    { validator: validateEmailUnique, trigger: "blur" },
  ],
  captcha: [{ validator: validateCaptcha, trigger: "blur" }],
});

const registerStore = useRegisterStore();
const router = useRouter();

function handlerPrevStep() {
  emit("prev");
}

function handlerRegister() {
  formRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const { ...submitdata } = registerStore.userInfo;
      submitdata.birthDate = dayjs(registerStore.userInfo.birthDate).format("YYYY-MM-DD");
      submitdata.captcha = captcha.value;
      registerStore
        .register({ ...submitdata })
        .then(async () => {
          registerStore.clear();
          ElMessage.success("注册成功");
          await userStore.getUserInfo();
          // // 跳转到注册前的页面
          const { path, queryParams } = parseRedirect();
          router.push({ path: path, query: queryParams });
        })
        .catch(() => {
          // ElMessage.error("注册失败");
        })
        .finally(() => {
          loading.value = false;
        });
    }
  });
}

function handlerCaptcha() {
  formRef.value.validate((valid: any) => {
    if (valid) {
      EmailApi.sendVerificationCode({
        email: registerStore.userInfo.email,
        browserId: appStore.browserId,
      }).then(() => {
        ElMessage.success("发送成功!");
        startCountdown(60);
        send.value = true;
      });
    }
  });
}

/**
 * 解析 redirect 字符串 为 path 和  queryParams
 *
 * @returns { path: string, queryParams: Record<string, string> } 解析后的 path 和 queryParams
 */
function parseRedirect(): {
  path: string;
  queryParams: Record<string, string>;
} {
  const query: LocationQuery = route.query;
  const redirect = (query.redirect as string) ?? "/";

  const url = new URL(redirect, window.location.origin);
  const path = url.pathname;
  const queryParams: Record<string, string> = {};

  url.searchParams.forEach((value, key) => {
    queryParams[key] = value;
  });

  return { path, queryParams };
}
onMounted(() => {
  if (!registerStore.userInfo.password) {
    router.push("/register/2");
  }
  // 异步加载并生成指纹
  FingerprintJS.load()
    .then((fp) => fp.get())
    .then((result) => {
      EmailApi.captchaTime(result.visitorId).then((data) => {
        if (data > 0) {
          startCountdown(data);
          send.value = true;
        }
      });
    });
});
</script>

<style lang="scss" scoped>
.submit-container {
  padding: 20px;
  .submit-content {
    min-height: 600px;
  }
  .mail-container {
    display: flex;
    justify-content: space-between;
  }
  .submit-footer {
    display: flex;
    justify-content: space-around;
  }
}
</style>
